<template>
  <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
    <a-form @submit="handleSubmit" :form="form">
      <a-form-item
        label="标题"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-decorator="['title', {rules: [{ required: true, message: '请输入标题' }]}]"
          name="name"
          placeholder="请输入标题"/>
      </a-form-item>

      <a-form-item
        label="范围"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        required
      >
        <a-radio-group
          v-decorator="['range_type', { initialValue: 1 }]">
          <a-radio :value="1">全体成员</a-radio>
          <a-radio :value="2">指定成员</a-radio>
        </a-radio-group>

        <a-form-item
          v-show="form.getFieldValue('range_type') === 2"
        >
          <a-input
            v-decorator="['designated_member', {}]"
            placeholder="请填写推送成员手机号，用,隔开"/>
        </a-form-item>
      </a-form-item>

      <a-form-item
        label="正文"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-textarea
          placeholder="请输入正文"
          :maxLength="200"
          :autoSize="{ minRows: 3, maxRows: 5 }"
          v-decorator="['content',{rules: [{ required: false, message: '请输入备注' }]}]"
        />
      </a-form-item>

      <a-form-item
        label="链接"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input
          v-decorator="['link', {}]"
          name="name"
          placeholder="请输入链接 (例如: http://www.baidu.com)"/>
      </a-form-item>

      <a-form-item
        label="图片"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <upload-pic
          :limit="1"
          v-decorator="['pic', { initialValue: [] }]"
        />
      </a-form-item>

      <a-form-item
        label="附件"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <upload-pic
          :limit="1"
          :accept="'.xls,.xlsx'"
          v-decorator="['attachment', { initialValue: [] }]"
          :preview="handleUploadAttachmentPreview"
        />
      </a-form-item>

      <a-form-item
        :wrapperCol="{ xs: { span: 24}, sm: { span: 16, offset: 2 } }"
      >
        <a-button htmlType="submit" type="primary">提交</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
  import { getWebsiteLetter, saveWebsiteLetter } from '@/api/proxy'
  import UploadPic from '@/components/UploadPic/UploadPic'

  export default {
    name: 'WebsiteLetterForm',
    components: { UploadPic },
    data () {
      return {
        labelCol: {
          xs: { span: 2 },
          sm: { span: 2 }
        },
        wrapperCol: {
          xs: { span: 8 },
          sm: { span: 8 }
        },

        // form
        form: this.$form.createForm(this)
      }
    },
    created () {
      if (this.$route.params.id) {
        getWebsiteLetter(this.$route.params.id).then(res => {
          // 初始化表单
          this.form.setFieldsValue({
            title: res.title,
            range_type: res.range_type,
            content: res.content,
            link: res.link,
            pic: res.attachments.filter(att => att.pivot.type === 1).map(att => {
              return {
                response: {
                  url: att.url,
                  id: att.id
                },
                mime_type: att.mime_type || '',
                name: att.id.toString(),
                url: att.url,
                uid: att.id
              }
            }),
            attachment: res.attachments.filter(att => att.pivot.type === 2).map(att => {
              return {
                response: {
                  url: att.url,
                  id: att.id
                },
                mime_type: att.mime_type || '',
                name: att.id.toString(),
                url: att.url,
                uid: att.id
              }
            })
          })

          this.$nextTick(_ => {
            this.form.setFieldsValue({
              designated_member: res.agent_letter && res.agent_letter.map(agentLetter => agentLetter.agent.phone).join(',')
            })
          })
        })
      }
    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (err) {
            this.$notification['error']({
              message: '表单填写有误:',
              description: values
            })
            return
          }
          this.$route.params.id && (values.id = this.$route.params.id) // 编辑的情况,赋值 id

          if (values.pic && values.pic.length > 0) {
            values.pic = values.pic.map(pic => pic.response.id)
          }
          if (values.attachment && values.attachment.length > 0) {
            values.attachment = values.attachment.map(attachment => attachment.response.id)
          }
          saveWebsiteLetter(values).then(res => {
            this.$notification.success({ message: '操作成功' })
            this.$router.push('/proxy/website-letter/list')
          })
        })
      },
      handleUploadAttachmentPreview (file) {
        return new Promise((resolve, reject) => {
          window.open(file.url)
          reject(new Error('nothing')) // 结束继续运行
        })
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader >>> .ant-upload {
    width: 128px;
    height: 128px;
  }

  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
</style>
